const express = require('express');
var jquery = require('cheerio');
const pathToRegexp = require('path-to-regexp');
const then = require('thenjs');
const fs = require('fs');
const path = require('path');
module.exports = class extends baseRouter {
    constructor() {
        super();
        this.nameSpace = '/';
        this.router = express.Router();
        this.DB = require("../../common/module/data-base");
    }

    static init() {
        return new this();
    }

    async getSiteModule(url) {
        let ret = {};
        let siteModules = await this.DB.cms_site_module.Access.findAll({
            raw: true
        });
        for (let i = 0; i < siteModules.length; i++) {
            let item = siteModules[i];
            let keys = [];
            let re = pathToRegexp(item.sm_url, keys);
            let match = re.exec(url, keys);
            if (match) {
                ret.curSiteModule = item;
                let names = keys.map(key => key.name);
                // 对一个数组进行处理
                ret.parmas = names.reduce((memo, name, idx) => {
                    memo[name] = match[idx + 1];
                    return memo;
                }, {});
                break;
            }
        }
        return ret;
    }

    getViewData(req) {
        let _viewData = {};
        let viewDataPath = path.join(path.resolve(), 'common', 'module', 'cms', 'config', 'view-data.json');
        let _viewDataPath = path.join(path.resolve(), 'common', 'module', 'cms', 'config', '_view-data.json');
        if (req && req.query.editModel) {
            //判断用户是否登陆
            if (fs.existsSync(_viewDataPath)) {
                _viewData = require(_viewDataPath);
            } else if (fs.existsSync(viewDataPath)) {
                _viewData = require(viewDataPath);
            } else {
                _viewData = null;
            }
        } else {
            _viewData = require(viewDataPath);
        }
        return _viewData;
    }

    GetRouter(app) {
        let self = this;

        app.use(this.nameSpace, async (req, res, next) => {
            try {

                let ret = await this.getSiteModule(req.url);
                if (ret.curSiteModule) {
                    console.log(ret);
                    let _viewData = this.getViewData(req);
                    if (!_viewData) {
                        next(new Error('请先发布站点'));
                    } else {
                        for (let key in ret.parmas) {
                            if (key) {
                                req.query[key] = ret.parmas[key];
                            }
                        }
                        let cms = require("../../common/module/cms").init(req);
                        cms.viewData = _viewData;
                        cms.curPage = ret.curSiteModule;
                        let tmp = require('./static/template/' + cms.siteInfo.siteTemplate + '/views/' + ret.curSiteModule.sm_viewPath);
                        then(function (defer) {
                            tmp.renderToString({
                                cms: cms
                            }, defer);
                        }).fin(function (defer, err, html) {
                            if (err) {
                                next(err);
                            } else {
                                res.send(html);
                                res.end();

                            }
                        });
                    }
                } else {
                    next();
                }
            } catch (err) {
                next(err);
            }
        });

        app.use(this.nameSpace, function (req, res, next) {
            let msg = `404 page no find. router.js -> this.nameSpace = ${self.nameSpace}, url wrong`;
            if (req.xhr) {
                let CB = {
                    Result: 0,
                    Msg: msg
                };
                res.json(CB);
            } else {
                let err = new Error(msg);
                err.status = 404;
                next(err);
            }

        });
    }
};